import React, { useState, useMemo } from 'react';
import { useNavigate, useParams } from 'react-router';
import { motion } from 'framer-motion';
import PatternDetail from '../components/PatternDetail';
import Sidebar from '../components/Sidebar';
import { patternsData } from '../data/patterns';
import { DesignPattern, PatternCategory } from '../types';

const PatternDetailPage: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [selectedCategory, setSelectedCategory] = useState<PatternCategory | 'all'>('all');
  const [selectedTab, setSelectedTab] = useState('overview');
  
  const pattern = patternsData.find(p => p.id === id);
  
  if (!pattern) {
    navigate('/');
    return null;
  }

  const filteredPatterns = useMemo(() => {
    if (selectedCategory === 'all') {
      return patternsData;
    }
    return patternsData.filter(pattern => pattern.category === selectedCategory);
  }, [selectedCategory]);

  const handleBack = () => {
    navigate('/');
  };

  const handleCategoryChange = (category: PatternCategory | 'all') => {
    setSelectedCategory(category);
  };

  const handlePatternSelect = (selectedPattern: DesignPattern) => {
    navigate(`/pattern/${selectedPattern.id}`);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div className="flex min-h-screen">
      <Sidebar
        patterns={filteredPatterns}
        selectedCategory={selectedCategory}
        onCategoryChange={handleCategoryChange}
        onPatternSelect={handlePatternSelect}
        currentPattern={pattern}
      />
      
      <main className="flex-1 relative">
        <motion.div
          key={`pattern-detail-${id}`}
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: -20 }}
          transition={{ duration: 0.3 }}
        >
          <PatternDetail
            pattern={pattern}
            selectedTab={selectedTab}
            demoState={{
              isRunning: false,
              isPaused: false,
              currentStep: 0,
              totalSteps: 0,
              output: [],
              visualization: null
            }}
            onBack={handleBack}
            onTabChange={setSelectedTab}
            onDemoStart={() => {}}
            onDemoPause={() => {}}
            onDemoReset={() => {}}
            onDemoStep={() => {}}
          />
        </motion.div>
      </main>
    </div>
  );
};

export default PatternDetailPage;
